#include "HLMasterServer.h"
#include "ServerInfo.h"
#include "HLServerInfo.h"

#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>

#include <stack>
#include <map>
#include <stdexcept>

#include <config.h>
#include <compat.h>

using namespace std;

HLMasterServer::HLMasterServer(const char *_addr, int port)
{
	char buf[BUFSIZ] = "";
	struct hostent he = {};
	int herrno = 0;
	struct hostent *result = NULL;

	memset(&addr, 0, sizeof(struct sockaddr_in));
	this->addr.sin_family = AF_INET;
	this->addr.sin_port = htons(port);

	if(gethostbyname_r(_addr, &he, buf, BUFSIZ, &result, &herrno) == 0) {
		memcpy(&this->addr.sin_addr.s_addr, he.h_addr_list[0], he.h_length);
	} else {
		throw invalid_argument("Unabe to resolve hostname");
	}
}

HLMasterServer::~HLMasterServer()
{
        while(!servers->empty()) {
                ServerInfo *s;
                s = servers->top();
                servers->pop();
                delete(s);
        }
	delete(servers);
}

ServerInfo * HLMasterServer::getServerInfo(const char *_addr, int _port)
{
	HLServerInfo *info = new HLServerInfo(_addr, _port);
	return info;
}
